﻿using MediatR;
using Production_Get.API.DTO;
using Production_Get.API.Infrastructures.Interfaces;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.Produce.Resources;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Get.API.Application.Commands.ResourcteShow
{
    /// <summary>
    /// 资源管理列表显示
    /// </summary>
    public class ResourceScretenHandler : IRequestHandler<ResourceScretenCommend, Result>
    {
        private readonly IBaseRepositoryGet<ResourceDtos> ResourceDtos;

        public ResourceScretenHandler(IBaseRepositoryGet<ResourceDtos> ResourceDtos)
        {
            this.ResourceDtos = ResourceDtos;
        }

        public async Task<Result> Handle(ResourceScretenCommend request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCodes.Search };

            string sql = "SELECT * FROM Resource a INNER JOIN ResourceType b on a.ResourceTypeId=b.ResourceTypeId INNER JOIN Expenses c on a.ExpensesId=c.ExpensesId INNER JOIN Benchmark d on a.BenchmarkId=d.BenchmarkId where a.IsDelete=0";
            ResourceDtos come = new ResourceDtos();
            var list = ResourceDtos.GetAll(sql, come).ToList();

            if (!string.IsNullOrEmpty(request.ResourceNo))
            {
                list = list.Where(x => x.ResourceNo.Contains(request.ResourceNo)).ToList();
            }

            if (!string.IsNullOrEmpty(request.ResourceName))
            {
                list = list.Where(x => x.ResourceName.Contains(request.ResourceName)).ToList();
            }

            if (request.ResourceTypeId > 0)
            {
                list = list.Where(x => x.ResourceTypeId == request.ResourceTypeId).ToList();
            }

            if (request.ResourceState != null)
            {
                list = list.Where(x => x.ResourceState == request.ResourceState).ToList();
            }

            var totalcount = list.Count();
            var pagecount = (int)Math.Ceiling(totalcount * 1.0 / request.pageSize);
            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            var lief = new
            {
                totalcount,
                pagecount,
                list,
            };

            if (list != null)
            {
                result.Code = (int)CommonErrorCodes.Success;
                result.Data = lief;
                result.Msg = "显示成功";
            }
            else
            {
                result.Msg = "显示失败";
            }
            return result;
        }
    }
}
